﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elderos.Highlight.Search;
using Elderos.Ontology;
using Elderos.Highlight;

namespace Elderos.Highlight.Rules
{
    [RankingRule("Capital", RuleType.SelfInfo)]
    public class RuleCapital : RankingRule
    {
        public RuleCapital(IOntologyData ontology) : base(ontology) { }

        /// <summary>
        /// Key - entity id, Value - country, whose capital it is
        /// </summary>
        private Dictionary<int, List<int>> _capitalMapping = new Dictionary<int, List<int>>(); 

        public override async Task Initialize(List<Func<HighlightResult, Task>> articleCacheInit)
        {
            await base.Initialize(articleCacheInit);
            int attID = Ontology.Attributes.First(x => x.Name == "/location/country/capital").ID;

            var attRefs = await Ontology.GetAttRefsAsync(new[] {attID});

            _capitalMapping = attRefs
                .GroupBy(x => x.ReferenceID)
                .ToDictionary(x => x.Key, x => new List<int>(x.Select(y => y.EntityID)));

        }

        public override IRuleResult EmptyResult
        {
            get { return new BinomialResult(Name, false);}
        }

#pragma warning disable 1998
        protected async override Task<Dictionary<TextEntity, IRuleResult>> InnerRank(HighlightResult highlightResult)
#pragma warning restore 1998
        {
            var results = new Dictionary<TextEntity, IRuleResult>();
		    foreach (var entity in highlightResult.Positions.SelectMany(x => x.EntitiesFlattened))
		    {
		        if (!_capitalMapping.ContainsKey(entity.EntityID)) continue;

                results.Add(entity, new BinomialResult(Name, true));
		    }

		    return results;
        }
    }
}
